import { createRouter, createWebHistory } from 'vue-router';

import { homeRoutes } from './modules/home'; // 首页

import type { RouteRecordRaw, RouteLocationNormalized } from 'vue-router';

import Layout from '@/layouts/index.vue';
import { requestStore } from '@/store/request';
import Page401 from '@/views/401.vue';
import Page404 from '@/views/404.vue';

const viteProjectRoot = import.meta.env.VITE_APP_ROOT;
const baseTitle = import.meta.env.VITE_APP_NAME_ZH;
let myRequestStore: TypeObject;

export const constantRoutes: Array<RouteRecordRaw> = [
  ...homeRoutes,
];

export const catchAllRoutes: Array<RouteRecordRaw> = [
  {
    path: '/error',
    component: Layout,
    redirect: '/error/404',
    meta: {
      hidden: true,
    },
    children: [
      {
        path: '/error/404',
        name: '404',
        component: Page404,
        meta: {
          hidden: true,
        },
      },
      {
        path: '/error/401',
        name: '401',
        component: Page401,
        meta: {
          hidden: true,
          hideAside: true,
        },
      },
      {
        path: '/:catchAll(.*)',
        redirect: '/error/404',
        meta: {
          hidden: true,
        },
      }
    ]
  },
];

const router = createRouter({
  history: createWebHistory(viteProjectRoot),
  routes: [...constantRoutes, ...catchAllRoutes],
  scrollBehavior: () => ({
    left: 0,
    top: 0,
  }),
});

router.afterEach((to: RouteLocationNormalized) => {
  setTimeout(() => {
    window.document.title = to.meta.title ? `${to.meta.title} | ${baseTitle}` : baseTitle;
  }, 0);
  if (!myRequestStore) {
    myRequestStore = requestStore();
  }
  // 页面切换清除所有的axios请求
  if (myRequestStore.requests && myRequestStore.requests.length > 0) {
    myRequestStore.requests.forEach((controller: any) => controller.abort()); // 通过遍历终止所有未完成的请求;
    myRequestStore.clearRequest();
  }
});

export default router;
